package com.grom.velocity;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import com.grom.constant.FileUtil;
import com.grom.constant.VelocityUtil;

public abstract class AbstractCreator {
	public abstract File getTargetFile(String templateFile);

	public void createFile(String templateFile) {
		try {
			VelocityContext context = VelocityUtil.buildVelocityContext(FileUtil.getSelectedStream());
			Template template = null;
			template = VelocityUtil.buildVelocityTemplate(templateFile);
			BufferedWriter writer;
			File file = getTargetFile(templateFile);
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			writer = new BufferedWriter(new FileWriter(file));
			if (template != null) {
				template.merge(context, writer);
			}
			writer.flush();
			writer.close();
		} catch (ResourceNotFoundException rnfe) {
			System.out.println("Example : error : cannot find template " + templateFile);
		} catch (ParseErrorException pee) {
			System.out.println("Example : Syntax error in template " + templateFile + ":" + pee);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
